/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.httpclient;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Map;
import java.util.Map.Entry;

import org.zhiqim.kernel.util.Stringx;
import org.zhiqim.kernel.util.Urls;
import org.zhiqim.kernel.util.Validates;

/**
 * HTTPS 文件上传类
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class HttpUpload extends HttpClient
{
    //上传文件和参数
    private String name;
    private String fileName;
    private byte[] fileContent;
    private String queryString;
    private boolean hasEncoded;
    
    //上传内容格式
    private String mimeType;
    private String encoding;
    private String boundary;
    
    public HttpUpload(String url)
    {
        super(url, _POST_);
        this.mimeType = _APPLICATION_OCTET_STREAM_;//默认字节流
        this.encoding = _UTF_8_;
        this.boundary = "" + System.currentTimeMillis();
    }
    
    /**
     * 添加文件内容
     * 
     * @param name          文件上传时使用的字段名称
     * @param fileName      文件名
     * @param fileContent   文件内容
     * @param encoding      文件编码
     */
    public void setContent(String name, String fileName, byte[] fileContent, String encoding)
    {
        this.name = Stringx.trim(name);
        this.fileName = Stringx.trim(fileName);
        this.fileContent = fileContent;
        this.encoding = Stringx.trim(encoding);
    }
    
    public void setEncoding(String encoding)
    {
        this.encoding = Stringx.trim(encoding);
    }
    
    public void setMimeType(String mimeType)
    {
        this.mimeType = Stringx.trim(mimeType);
    }
    
    public void setQueryString(String queryString, boolean hasEncoded)
    {
        this.queryString = Stringx.trim(queryString);
        this.hasEncoded = hasEncoded;
    }
    
    protected boolean doPreRequestProperty()
    {
        if (Validates.isEmpty(fileName) || fileContent == null)
        {
            responseStatus = _99_EXCEPTION_;
            responseText = "上传的文件名和内容不能为空";
            return false;
        }
        
        setDoOutput(true);
        addRequestProperty(_CONTENT_TYPE_, _MULTIPART_FORM_DATA_+"; charset="+encoding+"; boundary="+boundary);
        return true;
    }
    
    protected void doWriteRequestContent(HttpURLConnection conn) throws IOException
    {
        OutputStream out = conn.getOutputStream();
        byte[] entryBoundaryBytes = (_BR_ + "--" + boundary + _BR_).getBytes(encoding);

        // 输入文本请求参数
        Map<String, String> paramMap = null;
        if (hasEncoded)
            paramMap = Urls.toMap(queryString, encoding);
        else
            paramMap = Urls.toMapNoEncoded(queryString);
        
        for (Entry<String, String> entry : paramMap.entrySet()) 
        {
            byte[] textBytes = getTextDisposition(entry.getKey(), encoding);
            out.write(entryBoundaryBytes);
            out.write(textBytes);
            out.write(entry.getValue().getBytes(encoding));
        }

        // 输入文件请求参数
        byte[] fileBytes = getFileDisposition(name, fileName, mimeType, encoding);
        out.write(entryBoundaryBytes);
        out.write(fileBytes);
        out.write(fileContent);

        // 输入结束标志
        byte[] endBoundaryBytes = (_BR_ + "--" + boundary + "--" + _BR_).getBytes(encoding);
        out.write(endBoundaryBytes);
    }
}

